﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using TSOL.FastSPWeb.ValueObjects;
using TSOL.FastSPWeb.Core;

namespace TSOL.FastSPWeb
{
    public static partial class FastSPWebCallExtensions
    {
        public static void FastLists(this SPWeb Web, CachePolicy cachePolicy, Action<SPListCollection> outProc)
        {
            SPUser CurrentSPUser = Web.CurrentUser;
            Guid SiteGuid = Web.Site.ID;

            var hashKey = (SiteGuid.ToString() + Web.ID.ToString() + true.ToString() + CurrentSPUser.ID.ToString()).GetHashCode();

            SPListsCacheCollection _SPListsCacheCollection = null;
            SPListsCacheEntity _ListsCache = null;

            while (_ListsCache == null)
            {
                while (!FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.ListsCacheDictionary.TryGetValue(hashKey, out _SPListsCacheCollection))
                {
                    _SPListsCacheCollection = new SPListsCacheCollection() { UserUniqueID = CurrentSPUser.ID.ToString(), SiteGuid = SiteGuid, WebGuid = Web.ID };
                    FastSPListsFactory.BuildCollection(Web, CurrentSPUser.UserToken, hashKey, _SPListsCacheCollection);
                }

                _ListsCache = _SPListsCacheCollection.FirstOrDefault(a => a.Free == true);
                if (_ListsCache != default(SPListsCacheEntity))
                    break;
                else
                {
                    lock (_SPListsCacheCollection) _SPListsCacheCollection.WaitingForFreeLists++;
                    FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.FastSPListsWaitingForFreeCacheEntity++;
                }
            }
            lock (_ListsCache)
            {
                _ListsCache.Free = false;
                outProc(_ListsCache.Lists);
                _ListsCache.LastUsed = DateTime.Now;
                _ListsCache.Free = true;
            }
        }
    }
}